package com.bill99.golden.inf.sso.http;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bill99.golden.inf.sso.mdp.dto.CreateTokenRequestDto;
import com.bill99.golden.inf.sso.mdp.dto.DestroyTokenRequestDto;
import com.bill99.golden.inf.sso.mdp.dto.RefreshTokenTimeRequestDto;
import com.bill99.golden.inf.sso.mdp.dto.ValidateTokenRequestDto;
import com.bill99.golden.inf.sso.mdp.dto.ValidateTokenResponseDto;
import com.bill99.golden.inf.sso.service.TokenService;
import com.bill99.golden.inf.sso.util.CM;
import com.bill99.golden.inf.sso.util.Statistics;

public class TokenServiceHttp extends HttpServlet {
	private static Log log = LogFactory.getLog(TokenServiceHttp.class);
	private static final long serialVersionUID = -6923302211065874969L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>99BILL CAS SERVLET</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print("99BILL CAS SERVLET");
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String cmd = req.getParameter("cmd");
		// System.out.println("cmd=" + cmd);
		if ("registerSSO".equals(cmd)) {
			// 创建SSO令牌
			long st = System.currentTimeMillis();
			CreateTokenRequestDto r = new CreateTokenRequestDto();
			r.setAppCode(req.getParameter("appCode"));
			r.setUserId(req.getParameter("userId"));
			r.setUserIp(req.getParameter("userIp"));
			r.setExplorerType(req.getParameter("explorerType"));
			r.setUserCode(req.getParameter("userCode"));
			r.setUserName(req.getParameter("userName"));
			r.setOrgId(req.getParameter("orgId"));
			r.setOrgCode(req.getParameter("orgCode"));
			r.setOrgName(req.getParameter("orgName"));
			r.setDepartmentId(req.getParameter("departmentId"));
			r.setDepartmentCode(req.getParameter("departmentCode"));
			r.setDepartmentName(req.getParameter("departmentName"));
			r.setMemo(req.getParameter("memo"));
			String token = TokenService.createToken(r);
			long ed = System.currentTimeMillis();
			Statistics.addCreateLog(ed - st);
			log.debug("创建令牌成功：token=" + token);
			this.writeResponse(token, resp);
			return;
		} else if ("validateSSO".equals(cmd)) {
			// 验证SSO令牌
			long st = System.currentTimeMillis();
			ValidateTokenRequestDto r = new ValidateTokenRequestDto();
			r.setAppCode(req.getParameter("appCode"));
			r.setUserIp(req.getParameter("userIp"));
			r.setExplorerType(req.getParameter("explorerType"));
			r.setToken(req.getParameter("token"));
			r.setValidatePrivilege("true".equalsIgnoreCase(req
					.getParameter("validatePrivilege")));
			r.setVisitUrl(req.getParameter("visitUrl"));
			ValidateTokenResponseDto rt = TokenService.validateToken(r);
			StringBuffer sb = new StringBuffer();
			sb.append(rt.isValid()).append("!@!");
			sb.append(rt.getErrorCode()).append("!@!");
			sb.append(rt.getToken()).append("!@!");
			sb.append(rt.getUserId()).append("!@!");
			sb.append(rt.getUserCode()).append("!@!");
			sb.append(rt.getUserName()).append("!@!");
			sb.append(rt.getOrgId()).append("!@!");
			sb.append(rt.getOrgCode()).append("!@!");
			sb.append(rt.getOrgName()).append("!@!");
			sb.append(rt.getDepartmentId()).append("!@!");
			sb.append(rt.getDepartmentCode()).append("!@!");
			sb.append(rt.getDepartmentName()).append("!@!");
			sb.append(rt.getMemo()).append("!@!");
			sb.append(rt.getCheckCode()).append("!@!");
			//log.debug("validateSSOResponse:"+sb.toString());
			this.writeResponse(sb.toString(), resp);
			long ed = System.currentTimeMillis();
			Statistics.addValidateLog(ed - st);
			log.debug("验证令牌：" + r);
			return;
		} else if ("destroySSO".equals(cmd)) {
			// 销毁SSO令牌
			long st = System.currentTimeMillis();
			DestroyTokenRequestDto r = new DestroyTokenRequestDto();
			r.setAppCode(req.getParameter("appCode"));
			r.setUserIp(req.getParameter("userIp"));
			r.setExplorerType(req.getParameter("explorerType"));
			r.setToken(req.getParameter("token"));
			TokenService.destroyToken(r);
			long ed = System.currentTimeMillis();
			Statistics.addDestroyLog(ed - st);
			log.debug("销毁令牌：" + r);
			return;
		} else if ("refreshSSO".equals(cmd)) {
			// 销毁SSO令牌
			long st = System.currentTimeMillis();
			RefreshTokenTimeRequestDto r = new RefreshTokenTimeRequestDto();
			r.setAppCode(req.getParameter("appCode"));
			r.setUserIp(req.getParameter("userIp"));
			r.setExplorerType(req.getParameter("explorerType"));
			r.setToken(req.getParameter("token"));
			r.setVisitTimeSpan(CM.toLongObj(req.getParameter("timeSpan")));
			TokenService.refreshToken(r);
			long ed = System.currentTimeMillis();
			Statistics.addDestroyLog(ed - st);
			log.debug("销毁令牌：" + r);
			return;
		} else {
			log.error("TokenServiceHttp操作命令类型错误：cmd=" + cmd);
		}
	}

	private void writeResponse(String str, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("UTF-8");
		resp.setContentLength(str.getBytes("UTF-8").length);
		PrintWriter out = resp.getWriter();
		out.print(str);
		out.flush();
		out.close();
	}

	public static void main(String[] args) {
		String str = "!@!avc!@!!@!OK!@!!@!!@!";
		String t[] = str.split("!@!", 0);
		System.out.println("size=" + t.length);
		for (int i = 0; i < t.length; i++) {
			System.out.println(i + ":" + t[i]);
		}
	}
}
